<script setup lang="ts">
import Header from '@/components/Header.vue'
import Menu from '@/components/Menu.vue'
import MyBox from '@/components/MyBox.vue'
import EfficiencyChart from './components/EfficiencyChart.vue'
import YieldChart from './components/YieldChart.vue'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useMessage } from '@/hooks/useMessage'
import { Query } from '@/api'

//工单信息
const woFieldList = ref<any[]>([])
const woList = ref<any[]>([])

//完成率和总良率
const yieldFieldList = ref<any[]>([])
const yieldList = ref<any[]>([])
// 工单完成率 = 完成数量/(完成数量+未完成数量)
const woRate = ref('0')
// 良率 = 合格数/(合格数+不良数)
const okRate = ref('0')

const { query } = useRoute()
//看板标题
const title = computed(() => {
  return query.label || ''
})
//是否显示所有站点
const stationStatus = ref(false)
const currentIndex = ref(0);

//效率图
const efficiencyChartTitle = computed(() => {
  //根据station value取其label
  const match =
    (stationList.value.length &&
      stationList.value.filter((item: any) => item.Value == station.value)) ||
    []
  const label = match.length && match[0].Label
  return (
    `${(woList.value.length && woList.value[0]['WO']) || ''}${station.value ? '-' + label : ''}` +
    '效率图'
  )
})
const efficiencyChartInfo = ref({
  legendList: [],
  timeList: [],
  planList: [],
  actualList: []
})
//直通率
const yieldChartInfo = ref({
  legendList: [],
  timeList: [],
  targetList: [],
  actualList: []
})
//刷新周期
const flushTimer = ref()
//底部责任人
const otherInfo = ref({
  PD: '',
  QA: '',
  PE: ''
})

//线别
const line = ref('')
const lineList = ref()
//站别
const station = ref('')
const stationList = ref([])
//切换线别
const changeLine = async () => {
  station.value = ''
  //获取责任人信息
  const match =
    lineList.value.length && lineList.value.filter((item: any) => item.Value == line.value)

  //关闭定时循环
  stopTimer()
  //获取站别信息
  const res = (await Query({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=GetValue;$;Key=Station;$;Line=${line.value}`
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const { listInfo } = res.data
  stationList.value = listInfo || []
}

//获取数据
const getKBInfo = async () => {
  const res = (await Query({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=GetKBInfo;$;Key=Station;$;Line=${line.value};$;Station=${station.value}`
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const { woInfo, woInputInfo, capaInfo, fpyInfo,masterInfo } = res.data
  woList.value = woInfo || []
  yieldList.value = woInputInfo || []
  const { FinishQty, NonFinishQty, OKQty, NGQty } = woInputInfo.length && woInputInfo[0]
  // 工单完成率 = 完成数量/(完成数量+未完成数量)
  woRate.value = ((Number(FinishQty) / (Number(FinishQty) + Number(NonFinishQty))) * 100).toFixed(2)
  // 良率 = 合格数/(合格数+不良数)
  okRate.value = ((Number(OKQty) / (Number(OKQty) + Number(NGQty))) * 100).toFixed(2)
  // 格式化图表信息
  efficiencyChartInfo.value.timeList = capaInfo.map((item: any) => item.TimeNode)
  efficiencyChartInfo.value.actualList = capaInfo.map((item: any) => item.ActualQty)
  efficiencyChartInfo.value.planList = capaInfo.map((item: any) => item.PlanQty)

  yieldChartInfo.value.timeList = fpyInfo.map((item: any) => item.TimeNode)
  yieldChartInfo.value.actualList = fpyInfo.map((item: any) => item.ActualFPY)
  yieldChartInfo.value.targetList = fpyInfo.map((item: any) => item.TargetFPY)
  otherInfo.value = masterInfo.length && masterInfo[0]
}
//切换站别
const changeStation = async () => {
  if(line.value){
    // 先关闭定时器再重新启动刷新周期
    stopTimer()
    //选择站别之后，开始循环获取数据GetKBInfo
    startTimer()
  } else {
    message.error('请先选择线别')
  }
}

const message = useMessage()
//获取页面信息
const getPageInfo = async () => {
  const res = (await Query({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=Getpage`
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const { ctInfo, woFieldInfo, woInputFieldInfo, capaFieldInfo, fpyFieldInfo, lineInfo } = res.data
  woFieldList.value = woFieldInfo || []
  yieldFieldList.value = woInputFieldInfo.slice(0, 4)
  //获取图表图例
  efficiencyChartInfo.value.legendList =
    capaFieldInfo.slice(2, 4).map((item: any) => item.label) || []
  yieldChartInfo.value.legendList = fpyFieldInfo.slice(2, 4).map((item: any) => item.label) || []
  //刷新时间
  flushTimer.value = ctInfo.length && ctInfo[0].CT
  lineList.value = lineInfo || []
}

// 1.循环过程中，重新选择【线别】，关闭循环，选定【站别】后重新开始
// 2.循环过程中，重新选择【站别】，关闭循环并开始新循环

// 定义状态
const isRunning = ref(false)
const timerId = ref<number | null>(null)

// 开始定时器
const startTimer = async () => {
  if (isRunning.value) return // 防止重复启动

  isRunning.value = true
  console.log('定时器启动')

  // 立即执行一次
  if(stationStatus.value){
    station.value = stationList.value[currentIndex.value].Value;
  }
  await getKBInfo()

  // 设置定时器，每3分钟执行一次 (3分钟 = 3*60*1000 = 180000毫秒)
  const timer = flushTimer.value * 1000
  // timerId.value = window.setInterval(getKBInfo, timer)
  timerId.value = setInterval(async () => {
    // 切换到下一个站点
    if(stationStatus.value){
      currentIndex.value = (currentIndex.value + 1) % stationList.value.length;
      station.value = stationList.value[currentIndex.value].Value;
    }

    // 调用接口
    await getKBInfo();

    // 重置进度
  }, timer);

}

// 停止定时器
const stopTimer = () => {
  if (timerId.value) {
    window.clearInterval(timerId.value)
    timerId.value = null
    isRunning.value = false
    console.log('定时器已停止')
  }
}

// 组件卸载前清理定时器
onBeforeUnmount(() => {
  stopTimer()
})

onMounted(() => getPageInfo())
</script>
<template>
  <div class="w-full overflow-hidden my-page">
    <Header :title="`${title}` + '看板'" />
    <section class="board-content">
      <div class="flex justify-between row">
        <MyBox title="工单信息" style="width: 40%">
          <template v-slot:main>
            <div class="flex justify-between wo-item" v-for="item in woFieldList" :key="item.label">
              <p class="text-justify label">{{ item.label }}:</p>
              <p class="flex items-center text-right value">
                {{ (woList.length && woList[0][item.value]) || '' }}
              </p>
            </div>
          </template>
        </MyBox>
        <MyBox :title="efficiencyChartTitle" style="width: calc(60% - 30px)">
          <template v-slot:extra>
            <div class="flex extra">
              <el-switch style="margin-top: 4px" class="large-switch" size="large" inline-prompt active-text="自动" inactive-text="手动" @change="changeStation" v-model="stationStatus" />
              <div class="select-box">
                <el-select
                  v-if="!stationStatus"
                  v-model="station"
                  style="width: 170px;margin-left:10px"
                  placeholder="请选择站别"
                  @change="changeStation"
                >
                  <el-option
                    v-for="(item, index) in stationList"
                    :key="index"
                    :label="item.Label"
                    :value="item.Value"
                  />
                </el-select>
                <h4 class="current-station-box flex" v-else>{{ station }}</h4>
              </div>
              <div class="flex">
                <template v-for="(item, index) in efficiencyChartInfo.legendList" :key="index">
                  <p class="flex items-center">
                    {{ item }}
                  </p>
                </template>
              </div>
            </div>
          </template>
          <template v-slot:main>
            <EfficiencyChart :data="efficiencyChartInfo" />
          </template>
        </MyBox>
      </div>
      <div class="flex justify-between row">
        <MyBox title="完成率和总良率" style="width: 40%">
          <template v-slot:main>
            <div class="flex justify-around yield-list">
              <div class="relative yield-item" v-for="(item, index) in yieldFieldList" :key="index">
                <p class="label">{{ item.label }}</p>
                <p class="text-center value">
                  {{ (yieldList.length && yieldList[0][item.value]) || '-' }}
                </p>
              </div>
            </div>
            <div class="flex items-center justify-between wo-yield">
              <div class="flex items-center item yield">
                <div class="text-center rate">
                  <!-- 工单完成率 = 完成数量/(完成数量+未完成数量) -->
                  <p>
                    工单完成率<br /><span class="number">{{ woRate + '%' }}</span>
                  </p>
                </div>
                <div class="quantity">
                  <p class="flex items-center text-right">
                    未完成 {{ (yieldList.length && yieldList[0]['NonFinishQty']) || 0 }}
                  </p>
                  <p class="flex items-center text-right">
                    完成数 {{ (yieldList.length && yieldList[0]['FinishQty']) || 0 }}
                  </p>
                </div>
              </div>
              <div class="flex items-center item overall">
                <div class="text-center rate">
                  <!-- 良率 = 合格数/(合格数+不良数) -->
                  <p>
                    工单总良率<br /><span class="number">{{ okRate + '%' }}</span>
                  </p>
                </div>
                <div class="quantity">
                  <p class="flex items-center">
                    不良数 {{ (yieldList.length && yieldList[0]['NGQty']) || 0 }}
                  </p>
                  <p class="flex items-center">
                    良品数 {{ (yieldList.length && yieldList[0]['OKQty']) || 0 }}
                  </p>
                </div>
              </div>
            </div>
          </template>
        </MyBox>
        <MyBox
          :title="`${(woList.length && woList[0]['PN']) || ''}` + '直通率'"
          style="width: calc(60% - 30px)"
        >
          <template v-slot:extra>
            <div class="flex extra circle">
              <div class="flex">
                <template v-for="(item, index) in yieldChartInfo.legendList" :key="index">
                  <p class="flex items-center">
                    {{ item }}
                  </p>
                </template>
              </div>
            </div>
          </template>
          <template v-slot:main>
            <YieldChart :data="yieldChartInfo" />
          </template>
        </MyBox>
      </div>
      <div class="flex justify-between other-info">
        <MyBox title="" style="width: 100%">
          <template v-slot:main>
            <div class="flex items-center justify-between">
              <p>
                <el-select
                  v-model="line"
                  style="width: 170px"
                  placeholder="请选择线别"
                  @change="changeLine"
                >
                  <el-option
                    v-for="(item, index) in lineList"
                    :key="index"
                    :label="item.Label"
                    :value="item.Value"
                  />
                </el-select>
              </p>
              <p>生产责任人：{{ otherInfo.PD ?? '' }}</p>
              <p>质量责任人：{{ otherInfo.QA ?? '' }}</p>
              <p>工程责任人：{{ otherInfo.PE ?? '' }}</p>
            </div>
          </template>
        </MyBox>
      </div>
    </section>
    <Menu />
  </div>
</template>
<style lang="less" scoped>
.large-switch.is-checked{
  :deep(.el-switch__core){
    .el-switch__action{
      left: calc(100% - 34px)!important;
    }
  }
}
.large-switch {
  :deep(.el-switch__core) {
    height: 36px;
    min-width: 90px;
    border-radius: 20px;
    .el-switch__action{
      width: 34px;
      height: 34px;
    }
    &::after {
      width: 34px;
      height: 34px;
    }
  }

  :deep(.el-switch__inner) {
    font-size: 16px;
    .is-text{
      font-size: 18px
    }
  }
}
.extra {
  position: absolute;
  right: 30px;
  top: 10px;
  font-size: 22px;
  color: #8fe1ff;
  .select-box {
    margin-right: 20px;
  }
  p {
    padding-left: 10px;
    &:before {
      display: inline-block;
      content: '';
      width: 18px;
      height: 18px;
      margin-right: 10px;
      background: #00b8a9;
      border-radius: 2px;
    }
    &:first-child {
      &::before {
        background: #f7c873;
        border-radius: 50%;
      }
    }
  }
}
.extra.circle {
  top: 20px;
  p {
    &:before {
      border-radius: 50%;
    }
  }
}

.row {
  margin: 20px auto 20px;
}

.wo-item {
  width: 98%;
  margin: 22px auto;
  color: #8fe1ff;
  padding: 2px 20px;
  font-size: 24px;
  background: #085096;
  &:first-child {
    margin-top: 30px;
    border: 2px solid #00aeff;
  }
  .value {
    &:before {
      display: inline-block;
      content: '';
      width: 15px;
      height: 15px;
      margin-right: 10px;
      background: #00f2f1;
      border-radius: 50%;
    }
  }
}

.yield-list {
  margin: 20px auto 30px;
  background: rgba(18, 155, 255, 0.2);
  padding: 16px 0 10px;
  .yield-item:not(:last-child) {
    &::after {
      display: block;
      content: '';
      width: 2px;
      height: 54px;
      background: url('@/assets/wo-line.png') no-repeat center center;
      position: absolute;
      top: 14px;
      right: -52px;
    }
  }
  .label {
    font-size: 18px;
    color: #fff;
  }
  .value {
    height: 42px;
    margin-top: 10px;
    font-size: 28px;
    color: #2e95f8;
  }
}

.wo-yield {
  .item {
    .rate {
      width: 180px;
      height: 180px;
      padding-top: 50px;
      background: #48ffb2;
      color: #fff;
      border-radius: 50%;
      font-size: 18px;
      font-weight: 900;
      .number {
        font-size: 36px;
        font-weight: 400;
      }
    }
    .quantity {
      margin-left: 10px;
      color: #8fe1ff;
      font-size: 20px;
      p {
        &::before {
          display: block;
          content: '';
          width: 16px;
          height: 16px;
          margin-right: 8px;
        }
      }
    }
  }
  .yield {
    .quantity {
      p {
        &::before {
          background: #48ffb2;
        }
        &:last-child {
          &::before {
            background: #5fd5ec;
          }
        }
      }
    }
  }
  .overall {
    .rate {
      background: #5fd5ec;
    }
    .quantity {
      p {
        &::before {
          background: #eb6347;
        }
        &:last-child {
          &::before {
            background: #129bff;
          }
        }
      }
    }
  }
}

.other-info {
  color: #8fe1ff;
  font-size: 24px;
  .flex {
    width: 98%;
    margin: 0 auto;
  }
}

.el-select-dropdown__item {
  font-size: 18px;
}
.current-station-box{
  font-size: 22px;
  color: #8fe1ff;
  border: 1px solid #8fe1ff;
  padding:6px 10px;
  border-radius: 5px;
  margin-left: 10px;
}

</style>
